package com.kerbores.utils.baidu.common;

import java.util.HashMap;
import java.util.Map;

import org.nutz.http.Header;
import org.nutz.http.Request;
import org.nutz.http.Request.METHOD;
import org.nutz.http.Response;
import org.nutz.http.Sender;
import org.nutz.lang.util.NutMap;

import com.kerbores.utils.entries.Result;

/**
 * @author 王贵源
 * @email kerbores@kerbores.com
 *
 *        create at 2015年10月16日 上午11:53:24
 */
public class BaiduApiInvoker {

	protected static String ERROR_CODE_KEY = "errNum";
	protected static String DATA_KEY = "retData";
	protected static String ERROR_MSG_KEY = "retMsg";

	/**
	 * get调用
	 * 
	 * @param key
	 * @param endpoint
	 * @param data
	 * @return
	 */
	public static Result get(String key, String endpoint, NutMap data) {
		return invoke(key, endpoint, data, METHOD.GET);
	}

	/**
	 * post调用
	 * 
	 * @param key
	 * @param endpoint
	 * @param data
	 * @return
	 */
	public static Result post(String key, String endpoint, NutMap data) {
		return invoke(key, endpoint, data, METHOD.POST);
	}

	/**
	 * 百度接口调用器
	 * 
	 * @param key
	 *            appkey
	 * @param endpoint
	 *            调用点
	 * @param data
	 *            参数
	 * @param method
	 *            调用方式
	 * @return 接口返回值
	 */
	public static Result invoke(String key, String endpoint, NutMap data, METHOD method) {
		Map<String, String> properties = new HashMap<String, String>();
		properties.put("apikey", key);
		Request request = Request.create(endpoint, METHOD.GET, data, Header.create(properties));
		Sender sender = Sender.create(request);
		Response response = sender.send();
		if (response.getStatus() == 200) {
			String info = response.getContent();
			NutMap map = NutMap.WRAP(info);
			if (map.getInt(ERROR_CODE_KEY) == 0) {
				return Result.success(map.getAs(DATA_KEY, NutMap.class));
			}
			return Result.fail("调用错误, code: " + map.getInt("errNum") + " msg: " + map.getString(ERROR_MSG_KEY));// 响应错误码
		} else {
			return Result.fail("网络错误, code: " + response.getStatus());// 响应错误码
		}
	}

}
